import { Dropdown, Menu } from 'antd';
import React, { useMemo, useRef, useState } from 'react';

import type { MenuProps, MenuItemProps, DropDownProps } from 'antd';
import useWindowWidth from '@/hooks/event/use-window-width';
import { SvgIcon } from '../icon';

// 假设useSystem在hooks目录下，根据实际情况调整路径

export type MenuItemType = 'primary' | 'danger';

export type Props = {
  width?: number | string;
  offset?: [number, number];
  Button: React.ReactNode;
  trigger?: 'hover' | 'click';
  iconSize?: string;
  iconRadius?: string;
  placement?: DropDownProps['placement'];
  menuList: {
    label?: string;
    children: {
      isActive?: boolean;
      type?: MenuItemType;
      icon?: string;
      label: string | React.ReactNode;
      description?: string;
      onClick?: () => any;
      menuItemStyles?: MenuItemProps;
    }[];
  }[];
};

// 提取菜单项样式映射
const getTypeStyle = (type: MenuItemType): React.CSSProperties => {
  const typeMapStyle: Record<MenuItemType, React.CSSProperties> = {
    primary: {
      color: 'inherit',
    },
    danger: {
      color: '#f5222d',
    },
  };
  return typeMapStyle[type];
};

// 提取菜单项标签渲染
const renderMenuItemLabel = (
  item: Props['menuList'][0]['children'][0],
  onItemClick: () => void,
) => (
  <div
    style={{
      display: 'flex',
      alignItems: 'center',
      whiteSpace: 'pre-wrap',
      width: '100%',
    }}
    onClick={onItemClick}
  >
    {!!item.icon && <SvgIcon icon={item.icon} />}
    <div className="ml-2" style={{ width: '100%' }}>
      <div
        style={{
          width: '100%',
          color: item.description ? 'rgba(0, 0, 0, 0.9)' : 'inherit',
          fontSize: '14px',
        }}
      >
        {item.label}
      </div>
      {item.description && (
        <div
          style={{
            color: 'rgba(0, 0, 0, 0.45)',
            fontSize: '12px',
            width: '100%',
          }}
        >
          {item.description}
        </div>
      )}
    </div>
  </div>
);

// 提取单个菜单项构建
const buildMenuItem = (
  item: Props['menuList'][0]['children'][0],
  groupIndex: number,
  itemIndex: number,
  onItemClick: () => void,
) => {
  const key = `${groupIndex}-${itemIndex}`;
  const baseStyle = item.type ? getTypeStyle(item.type) : getTypeStyle('primary');
  const style = {
    ...baseStyle,
    ...(item.isActive ? { color: '#0070cc' } : {}),
    ...(item.menuItemStyles as unknown as React.CSSProperties),
  };

  return {
    key,
    label: renderMenuItemLabel(item, onItemClick),
    style,
    ...(item.type === 'danger' ? { danger: true } : {}),
  };
};

// 提取分组菜单项构建
const buildGroupItems = (
  group: Props['menuList'][0],
  groupIndex: number,
  onItemClick: (item: Props['menuList'][0]['children'][0]) => void,
) => {
  return group.children.map((item, itemIndex) =>
    buildMenuItem(item, groupIndex, itemIndex, () => onItemClick(item)),
  );
};

// 提取分组标题和分隔线
const buildGroupWithTitle = (
  group: Props['menuList'][0],
  groupIndex: number,
  groupItems: any[],
  isLastGroup: boolean,
) => {
  const items = [
    {
      key: `group-${groupIndex}-title`,
      label: <div style={{ fontSize: '14px' }}>{group.label}</div>,
      type: 'group' as const,
    },
    ...groupItems,
  ];

  if (!isLastGroup) {
    items.push({ key: `divider-${groupIndex}`, type: 'divider' as const });
  }

  return items;
};

// 提取分组菜单项（无标题）
const buildGroupWithoutTitle = (groupItems: any[], groupIndex: number, isLastGroup: boolean) => {
  const items = [...groupItems];

  if (!isLastGroup) {
    items.push({ key: `divider-${groupIndex}`, type: 'divider' as const });
  }

  return items;
};

function MyMenu({
  width = 'auto',
  trigger = 'hover',
  offset,
  iconSize = '1rem',
  Button,
  menuList,
  iconRadius,
  placement = 'bottomLeft',
}: Props) {
  // useSystem hook应提供isPc属性，如果不存在，可能需要创建
  const { isPc } = useWindowWidth();
  const closeTimer = useRef<any>();
  const [isOpen, setIsOpen] = useState(false);

  const formatTrigger = !isPc ? 'click' : trigger;

  // 处理菜单关闭
  const handleVisibleChange = (visible: boolean) => {
    if (formatTrigger === 'hover') {
      clearTimeout(closeTimer.current);
      if (!visible) {
        closeTimer.current = setTimeout(() => {
          setIsOpen(false);
        }, 100);
      } else {
        setIsOpen(true);
      }
    } else {
      setIsOpen(visible);
    }
  };

  // 处理菜单项点击
  const handleItemClick = (item: Props['menuList'][0]['children'][0]) => {
    if (item.onClick) {
      setIsOpen(false);
      item.onClick();
    }
  };

  // 构建菜单项
  const items: MenuProps['items'] = useMemo(() => {
    return menuList
      .map((group, groupIndex) => {
        const groupItems = buildGroupItems(group, groupIndex, handleItemClick);
        const isLastGroup = groupIndex === menuList.length - 1;

        if (group.label) {
          return buildGroupWithTitle(group, groupIndex, groupItems, isLastGroup);
        }

        return buildGroupWithoutTitle(groupItems, groupIndex, isLastGroup);
      })
      .flat();
  }, [menuList, iconRadius, iconSize]);

  return (
    <Dropdown
      open={isOpen}
      onOpenChange={handleVisibleChange}
      trigger={[formatTrigger]}
      placement={placement}
      arrow={false}
      dropdownRender={() => (
        <Menu
          style={{
            minWidth: typeof width === 'number' ? `${width}px` : width,
            maxWidth: '300px',
            padding: '6px',
            boxShadow:
              '0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05)',
          }}
          items={items}
        />
      )}
    >
      <div
        style={{
          position: 'relative',
          color: isOpen ? '#0070cc' : '',
          width: 'fit-content',
          padding: '4px',
          // backgroundColor: isOpen ? 'rgba(0, 0, 0, 0.04)' : '',
          height: 'fit-content',
          borderRadius: '2px',
        }}
      >
        {Button}
      </div>
    </Dropdown>
  );
}

export default React.memo(MyMenu);
